<template>
  <div>
    <layout>
      <!-- <keep-alive> -->
      <router-view />
      <!-- </keep-alive> -->
    </layout>

    <vm-back-top :bottom="100" :duration="1000" :timing="'ease'">
      <div class="backtop">
        <img :src="backTopImg" alt />
      </div>
    </vm-back-top>

    <div
      class="shareInfoContainer"
      v-show="!$route.meta.hideTabbar && getSupInfoWx.nickname"
      style="bottom:50px"
    >
      <div class="shareInfoFlex">
        好友
        <van-image
          round
          width=".22rem"
          height=".22rem"
          :src="getSupInfoWx.headImgUrl"
          style="margin:0 4px"
        />
        {{decodeutf16(getSupInfoWx.nickname)}}正在邀请你参加活动
      </div>
    </div>
    <van-tabbar
      v-model="activeTab"
      v-show="!$route.meta.hideTabbar"
      active-color="#0a589e"
      inactive-color="#000"
      @change="tabChange"
    >
      <van-tabbar-item icon="home-o">首页</van-tabbar-item>
      <van-tabbar-item icon="tv-o">直播</van-tabbar-item>
      <van-tabbar-item icon="shop-o">门店信息</van-tabbar-item>
      <van-tabbar-item icon-prefix="tenon" icon="icon-share" @click.native="openShare">分享</van-tabbar-item>
      <van-tabbar-item v-if="staffInfo" icon="user-o">店员中心</van-tabbar-item>
    </van-tabbar>
    <van-popup v-model="sharePopupVisible" class="sharePopup" position="top">
      <div class="sharePopupCon" @click="closeSharePopup">
        <img class="sharePopupImg" :src="sharePopupImg" alt />
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Tabbar, TabbarItem, Toast, Icon, Image, Popup, Dialog } from "vant";
import { mapMutations, mapActions, mapGetters } from "vuex";
import Layout from "./components/layout";
import wxJSFn from "@/js/wxJSFn";
import {
  shareConfig,
  shareConfig2,
  createShareUrl,
  shareRouter,
  shareImg
} from "@/config/shareConfig";
import { formatAvatarList, post } from "@/js/utils";
import qs from "qs";
import backTopImg from "@/assets/返回顶部.png";
import sharePopupImg from "@/assets/恭喜.png";
import wx from "weixin-js-sdk";
import { utf16toEntities, uncodeUtf16 } from "@/js/utils";
export default {
  components: {
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem,
    [Icon.name]: Icon,
    [Image.name]: Image,
    [Popup.name]: Popup,
    Layout
  },
  data() {
    return {
      activeTab: 0,
      backTopImg,
      sharePopupImg,
      sharePopupVisible: false
    };
  },
  computed: {
    shareParams() {
      return this.$store.state.shareParams;
    },
    activityMsg() {
      return this.$store.state.activityMsg;
    },
    supInfo() {
      return this.$store.state.activity.supInfo;
    },
    dataReady() {
      return {
        isReady: this.$store.state.activity.isReady,
        ...this.$store.state.shareParams,
        $route: this.$route //但路由改变的时候要重新写分享路径
      };
    },
    appData() {
      return this.$store.state.appData;
    },
    userId() {
      return this.$store.state.userId;
    },
    staffInfo() {
      return this.$store.state.staffInfo;
    },
    ...mapGetters({
      getSupInfoWx: "activity/getSupInfoWx"
    })
  },
  watch: {
    appData: {
      deep: true,
      immediate: true,
      handler(val, oldVal) {
        console.log("appDataChange", val, oldVal);
        if (val && val.resQuery && val.jsApiTicket) {
          this.doBusiness(val.resQuery, val.jsApiTicket);
        }
      }
    },
    userId: {
      deep: true,
      immediate: true,
      handler(val, oldVal) {
        if (val) {
          this.getEnrollInfo({
            wxOpenId: this.$store.state.userId
          });
        }
      }
    },
    dataReady: {
      deep: true,
      immediate: true,
      handler(val, oldVal) {
        if (val) {
          if (val.isReady && (val.pId || val.shareId)) {
            let obj = {
              aid: this.$store.state.aid
            };
            let link = "";
            let sConfig = shareConfig2;
            // if (this.shareParams.pId) obj.pid = this.shareParams.pId;
            if (this.shareParams.shareId)
              obj.shareId = this.shareParams.shareId;
            console.log("ready", this.staffInfo);
            if (this.staffInfo) {
              if (this.$store.state.activity.supInfoMy.id) {
                //当前人有发起过助力
                sConfig = shareConfig;
                link = createShareUrl(
                  obj,
                  this.$route.path,
                  shareRouter.supRouter
                );
              } else {
                //都没有
                link = createShareUrl(
                  obj,
                  this.$route.path,
                  shareRouter.actRouter
                );
              }
            } else {
              if (this.$store.state.activity.supInfoMy.id) {
                //当前人有发起过助力
                sConfig = shareConfig;
                link = createShareUrl(
                  obj,
                  this.$route.path,
                  shareRouter.supRouter
                );
              } else if (this.activityMsg.srAsId) {
                //当前页有助力
                let par1 = window.location.href.split("#")[0];
                let par2 = par1.split("?")[1];
                let param = qs.parse(par2);
                // if (param.pid) obj.pid = param.pid;
                if (param.shareId) obj.shareId = param.shareId;
                sConfig = shareConfig;
                link = createShareUrl(
                  obj,
                  this.$route.path,
                  shareRouter.supRouter
                );
              } else {
                //都没有
                link = createShareUrl(
                  obj,
                  this.$route.path,
                  shareRouter.actRouter
                );
              }
            }

            console.log("shareLink", link);
            wxJSFn.share({
              ...sConfig,
              link,
              imgUrl: shareImg
            });
          }
        }
      }
    }
  },
  created() {
    document.title = "天能九周年 四川巡礼";
    if ([0, 1, 2, 3, 4].includes(this.$route.meta.activeTab)) {
      this.activeTab = this.$route.meta.activeTab;
    }
  },
  mounted() {
    this.getSupNum();
  },
  methods: {
    ...mapActions({
      getSupNum: "activity/getSupNum",
      startSup: "activity/startSup",
      supFriend: "activity/supFriend",
      getSupInfo: "activity/getSupInfo",
      updateShareAndSup: "activity/updateShareAndSup",
      getUserSupId: "activity/getUserSupId",
      getEnrollInfo: "activity/getEnrollInfo",
      getStaffInfo: "getStaffInfo"
    }),
    ...mapMutations({
      setSupInfoMy: "activity/setSupInfoMy",
      pageReady: "activity/pageReady",
      setAvListMy: "activity/setAvListMy",
      setSupInfo: "activity/setSupInfo",
      setShareParams: "setShareParams",
      setActivityMsg: "setActivityMsg",
      setUserInfo: "setUserInfo",
      setAvList: "activity/setAvList"
    }),
    isHasCurSup() {
      this.getUserSupId({
        wxOpenId: this.$store.state.userId
      })
        .then(res => {
          if (res && res.code == "000000") {
            //当前登录人有发起过助力
            this.setSupInfoMy(res.data);
            return this.getSupInfo({
              assistId: res.data.id
            });
          }
          return undefined;
        })
        .then(res => {
          this.pageReady();
          if (res && res.code == "000000") {
            let list = formatAvatarList(res.data);
            this.setAvListMy(list);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    closeSharePopup() {
      this.sharePopupVisible = false;
    },
    tabChange(e) {
      switch (e) {
        case 0: {
          if (this.$route.name != "act7index") {
            this.$router.replace({
              name: "act7index",
              query: {
                ...this.$route.query
              }
            });
          }

          break;
        }
        case 1: {
          if (this.$route.name != "livePage") {
            this.$router.replace({
              name: "livePage",
              query: {
                ...this.$route.query
              }
            });
          }
          break;
        }
        case 2: {
          if (this.$route.name != "act7shop") {
            this.$router.replace({
              name: "act7shop",
              query: {
                ...this.$route.query
              }
            });
          }

          break;
        }
        case 3: {
          // this.$router.replace({
          //   name: "act7share",
          //   query: {
          //     ...this.$route.query
          //   }
          // });
          this.sharePopupVisible = true;
          break;
        }
        case 4: {
          if (this.$route.name != "staffPage") {
            this.$router.replace({
              name: "staffPage",
              query: {
                ...this.$route.query
              }
            });
          }

          break;
        }
      }
    },
    openShare(e) {
      console.log(e);
      e.preventDefault();
      this.sharePopupVisible = true;
    },
    doBusiness: async function(resQuery, jsApiTicket) {
      console.log("doBusiness", resQuery, jsApiTicket);
      let shareNew = {};
      let params = {};
      let self = this;
      let mySupAvatarRes = null;
      let isAssist = await this.getUserSupId({
        wxOpenId: this.$store.state.userId
      });
      let curAsId = ""; //当前登录人助力id
      let myAsInfo = null;
      if (isAssist.code == "000000") {
        this.setSupInfoMy(isAssist.data);
        curAsId = isAssist.data.id;
        mySupAvatarRes = await this.getSupInfo({
          assistId: isAssist.data.id
        });
        if (mySupAvatarRes.code == "000000") {
          let list = formatAvatarList(mySupAvatarRes.data);
          this.setAvListMy(list);
        }
      }
      let isStaff = await this.getStaffInfo({
        wxOpenId: this.$store.state.userId
      });
      let postMsg = {};
      console.log("isStaff", isStaff);
      if (isStaff) {
        postMsg = await post("/port/activity/getPlayBillByWxOpenId", {
          wxOpenId: this.$store.state.userId
        });
        console.log("postMsg", postMsg);
      }
      if (typeof resQuery.shareId != "undefined" && resQuery.shareId != null) {
        let share = await post("/port/activity/getActByShareId", {
          shareId: resQuery.shareId
        });
        if (share) {
          if (share.srToShareOpenid != this.$store.state.userId) {
            //非分享人打开了活动连接,通过海报生成本次分享
            shareNew = await post("/port/activity/activityShare", {
              shareOpenId: share.srToShareOpenid,
              toShareOpenId: this.$store.state.userId,
              pbId: share.pbId,
              assistId: curAsId ? curAsId : share.srAsId ? share.srAsId : ""
            });
            Object.assign(params, { shareId: shareNew.id });
            if (share.srAsId) {
              //获取助力信息
              let shareInfo = null;
              shareInfo = await this.getSupInfo({
                assistId: share.srAsId
              });
              if (shareInfo.code == "000000") {
                let list = formatAvatarList(shareInfo.data);
                this.setAvList(list);
                this.setSupInfo(shareInfo.portActivityAssist);
              }
            }
          } else {
            //当前人打开自己分享链接
            Object.assign(params, { shareId: resQuery.shareId });
            if (mySupAvatarRes && mySupAvatarRes.portActivityAssist) {
              this.setSupInfo(mySupAvatarRes.portActivityAssist);
              let list = formatAvatarList(mySupAvatarRes.data);
              this.setAvList(list);
            }
          }
          this.setActivityMsg(share);
        }
      } else {
        console.info("缺少参数海报id或分享id");
        console.log("postMsg", postMsg);
        if (postMsg && postMsg.id) {
          params.pId = postMsg.id;
          shareNew = await post("/port/activity/activityShare", {
            shareOpenId: this.$store.state.userId,
            toShareOpenId: this.$store.state.userId,
            pbId: postMsg.id,
            assistId: curAsId || ""
          });
          Object.assign(params, { shareId: shareNew.id });
        } else {
          console.log("非店员生成shareId");
          shareNew = await post("/port/activity/activityShare", {
            shareOpenId: this.$store.state.userId,
            toShareOpenId: this.$store.state.userId,
            pbId: 1,
            assistId: curAsId || ""
          });
          Object.assign(params, { shareId: shareNew.id });
          console.log("非店员params", params);
          // Toast("获取页面信息失败，请联系客服人员");
        }
        this.setActivityMsg({ id: 0 });
      }
      console.log("4", isStaff, shareNew.id, postMsg, postMsg.id);
      if (isStaff && postMsg && postMsg.id) {
        //员工打开分享出来的链接，将shareId更改为员工自己的shareId
        params.pId = postMsg.id;
        let shareNew2 = await post("/port/activity/activityShare", {
          shareOpenId: this.$store.state.userId,
          toShareOpenId: this.$store.state.userId,
          pbId: postMsg.id,
          assistId: curAsId || ""
        });
        console.log("shareNew2", shareNew2);
        params = {
          shareId: shareNew2.id
        };
      }

      this.setShareParams(params);
      this.pageReady();
      // if (typeof resQuery.pid != "undefined" && resQuery.pid != null) {
      //   let hb = await post("/port/activity/getActByPbId", {
      //     pbId: resQuery.pid
      //   });
      //   if (hb) {
      //     this.setActivityMsg(hb);
      //     if (hb.pbSourceOpenid != this.userId) {
      //       //非海报所有者打开了活动连接,通过海报生成本次分享
      //       shareNew = await post("/port/activity/activityShare", {
      //         shareOpenId: hb.pbSourceOpenid,
      //         toShareOpenId: this.userId,
      //         pbId: resQuery.pid
      //       });
      //       Object.assign(params, { shareId: shareNew.id });
      //     } else {
      //       Object.assign(params, { pId: resQuery.pid });
      //     }
      //   }
      // } else
    },
    decodeutf16(value) {
      return uncodeUtf16(value);
    }
  }
};
</script>

<style lang="scss">
.backTopBtnCon {
  position: fixed;
  right: 8px;
  width: 100px;
  height: 100px;
  background-color: white;
}
.backtop {
  width: 60px;
  height: 60px;
  // background-color: grey;
  border-radius: 50%;
  text-align: center;
  display: flex;
  align-items: center;
  img {
    width: 100%;
    height: 100%;
  }
}
.shareInfoContainer {
  position: fixed;
  left: 0;
  width: 100vw;
  padding: 12px 20px;
  font-size: 0.16rem;
  background-color: rgba(0, 0, 0, 0.527);
  color: white;
  border-radius: 15px 15px 0 0;
  box-sizing: border-box;
  .shareInfoFlex {
    display: flex;
    align-items: center;
  }
}
.sharePopup {
  background: transparent;
  .sharePopupCon {
    width: 100vw;
    .sharePopupImg {
      width: 100%;
    }
  }
}
</style>